package com.misty.api.WebSocket;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.misty.common.Util.RedisCache;
import com.misty.common.constants.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint(value = "/chatroomserver/{username}")
@Component
@Slf4j
public class WebSocketServer {

    @Autowired
    private RedisCache redisCache  = SpringUtil.getBean(RedisCache.class);

    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        JSONObject jsonObject;
        sessionMap.put(username, session);

        //发送在线列表
        this.sendUsers();

        //发送缓存聊天记录
        JSONObject messageListJson = new JSONObject();
        List<JSONObject> cacheList = redisCache.getCacheList(RedisKey.CHAT_MESSAGE + username);
        if(CollectionUtil.isNotEmpty(cacheList)){
            JSONArray array = JSONUtil.parseArray(cacheList);
            messageListJson.set("messages",array);
            this.sendMessage(JSONUtil.toJsonStr(messageListJson),session);
            redisCache.delCacheList(RedisKey.CHAT_MESSAGE + username);
        }
    }

    private void sendUsers() {
        JSONObject jsonObject;
        //发送在线列表
        JSONObject charListJson = new JSONObject();
        JSONArray charList = new JSONArray();
        for (Object key : sessionMap.keySet()) {
            jsonObject = new JSONObject();
            jsonObject.set("username", key);
            charList.add(jsonObject);
        }
        charListJson.set("users",charList);
        this.sendAllMessage(JSONUtil.toJsonStr(charListJson));
    }

    @OnClose
    public void onClose(Session session, @PathParam("username") String username) {
        sessionMap.remove(username);
        //更新在线用户列表
        this.sendUsers();
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("username") String username) {
//        //更新在线用户列表
//        this.sendUsers();

        JSONObject json = JSONUtil.parseObj(message);
        String fromUsername = json.getStr("from"); // 发送人
        String toUsername = json.getStr("to"); // 接收人
        String text = json.getStr("text"); // 发送的消息文本

        // 根据 to用户名来获取 session，再通过session发送消息文本
        Session toSession = sessionMap.get(toUsername);

        JSONObject jsonObject = new JSONObject();
        jsonObject.set("from", username);  // 发送人
        jsonObject.set("to", toUsername);  // 接收人
        jsonObject.set("text", text);  // text 同上面的text

        if(ObjectUtil.isNull(toSession)){
            //目前该用户不在线,redis缓存消息,最多缓存两小时消息
            List<JSONObject> cacheList;
            if(redisCache.existCacheList(RedisKey.CHAT_MESSAGE + toUsername)){
                cacheList = redisCache.getCacheList(RedisKey.CHAT_MESSAGE + toUsername);
            }else {
                cacheList = new ArrayList<>();
            }
            cacheList.add(json);
            redisCache.setCacheList(RedisKey.CHAT_MESSAGE + toUsername,cacheList);
            log.info("发送失败");
        }else {
            this.sendMessage(jsonObject.toString(), toSession);
        }

    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    private void sendMessage(String message, Session toSession) {
        try {
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("发送消息失败");
        }
    }

    private void sendAllMessage(String message) {
        try {
            for (Session session : sessionMap.values()) {
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }
}
